LOG_FILE="/var/log/auto_build.log"
FIRST_RUN=1
PRJ_LIST=""
BASE_ISO_PATH="/opt"
BUILD_ARCH=""
BUILD_PATH="/srv/obs/build"
CREATE_TAR_LIST=""
PRJ_CONF_FILE="deliver.conf"
CUR_PATH=`pwd`
GET_BASELINE_LIST=""
OBS_CACHE_PATH="/srv/cache/obs/tar_scm/repo/"
#record_log $LINENO ERROR "The building is error."

function exec_cmd()
{
    cmd=$1
    m_ip=$2
    m_user=$3
    m_pass=$4

    expect <<-END
set timeout -1
       spawn ssh -o "ConnectTimeout 180" $m_user@$m_ip "$cmd"
    expect {
        "(yes/no?)" {
            send "yes\r"
            expec "*assword*" {
                send "$m_pass\r"
            }
        }
        "(yes/no)?" {
            send "yes\r"
            expec "*assword*" {
                send "$m_pass\r"
            }
        }
        "\[P|p]assword:" {
            send "$m_pass\r"
        }
        timeout {
            send_user "connection to $m_ip timed out: \$expect_out(buffer)\n"
            exit 13
        }
           eof {
            catch wait result
            exit [lindex \$result 3]
            interact
        }
    }
    expect {
        eof {
            catch wait result
            exit [lindex \$result 3]
        }
        "\[P|p]assword:" {
            send_user "Invalid password or account.\$expect_out(buffer)\n"
            exit 13
        }
        timeout {
            send_user "connection to $m_ip timed out: \$expect_out(buffer)\n"
            exit 13
        }
    }
END
    return $?
}

function exec_scp(){
    m_res=$1
    m_des=$2
    m_pass=$3
    expect <<-END
set timeout -1
    spawn scp -o "ConnectTimeout 180" $m_res $m_des
    expect {
        "(yes/no?)" {
            send "yes\r"
            expect "*assword*" {
                send "$m_pass\r"
            }
        }
        "*assword*" {
            send "$m_pass\r"
        }
        eof {
            catch wait result
            exit [lindex \$result 3]
            interact"
        }
    }
    expect {
        eof {
            catch wait result
            exit [lindex \$result 3]
        }
        "*assword*" {
            send_user "Invalid password or account.\$expect_out(buffer)\n"
            exit 13
        }
    }
END
    return $?
}

function record_log(){
    local line_num=$1
    local level="$2"
    local log_content="$3"
    local cur_date=`date +"%F %a %r"`
    local host_name=`hostname`

    if [ $FIRST_RUN -ne 0 ];then
        FIRST_RUN=0
        rm -rf $LOG_FILE
    fi

    case $level in
        ERROR|WARNING|INFO)
        echo "[$cur_date] ${level}[$host_name][$0:$line_num]: $log_content" >>$LOG_FILE
        ;;
        *)
        echo "[$cur_date] ${level}[$host_name][$0:$line_num]: unsupported log type." >>$LOG_FILE
        exit 1
        ;;
    esac
}

function source_install()
{
    SOURCE_TAR="$1"
    SOURCE_DIR=${SOURCE_TAR%%.tar.gz}
    rm -rf /srv/cache/obs/tar_scm/repo/*
    tar -xf /opt/$SOURCE_TAR -C /srv/cache/obs/tar_scm
    mv /srv/cache/obs/tar_scm/$SOURCE_DIR/* /srv/cache/obs/tar_scm/repo
    rm -rf /srv/cache/obs/tar_scm/$SOURCE_DIR
}

function get_prj_list(){
    local prj_name=$1
    local prj_conf=$2
    local get_flag=1
    PRJ_LIST=""

    while read line
    do
        echo "$line" | grep "^#" 1>/dev/null 2>&1
        if [ -z "$line" -o  $? -eq 0 ];then
            continue
        fi
        if [ "$prj_name" != "create_tar_list" ];then
            echo "$line" | grep "=" 1>/dev/null 2>&1
            if [ $? -eq 0 ];then
                continue
            fi
        fi

        echo "$line" | grep "\[" 1>/dev/null 2>&1
        if [ $? -eq 0 ];then
            echo "$line" | grep "\[$prj_name\]" 1>/dev/null 2>&1
            if [ $? -eq 0 ];then
                get_flag=0
            else
                get_flag=1
            fi
            continue
        fi
        if [ $get_flag == 0 ];then
            PRJ_LIST="$PRJ_LIST$line "
        fi
    done <$prj_conf
}

function get_create_V2R8_tar_list(){
        prj_conf=$1
        CREATE_TAR_LIST=""

        grep create_tar_list $prj_conf >/dev/null 2>&1
        if [ $? -ne 0 ];then
                return 1
        fi

        get_prj_list create_tar_list $prj_conf
        for line in $PRJ_LIST
        do
                if [ -z "$line" ];then
                        return 1
                fi

                echo $line | grep "=" 1>/dev/null 2>&1
                if [ $? -ne 0 ];then
                        echo "Warning: $line is Invalid configuration."
                        continue;
                fi

                enable_list=${line%%"="*}

                enable_flag=${line##*"="}
                if [ "$enable_flag" == "yes" -o "$enable_flag" == "no" ];then
                        if [ "$enable_flag" == "yes" ];then
                                CREATE_TAR_LIST="$CREATE_TAR_LIST$enable_list "
                        fi
                else
                       NOT_CREATE_TAR_LIST="$CREATE_TAR_LIST$enable_list "
                fi
        done
}

function get_build_arch(){
    BUILD_ARCH=""
    local prj_conf=$1
    get_prj_list build_arch_configure $prj_conf
    if [ -z "$PRJ_LIST" ];then
        return 1
    fi

    for arch_name in $PRJ_LIST
    do
        arch_name=`echo $arch_name | tr -s ' '`
        case $arch_name in
            x86_64|aarch64)
                BUILD_ARCH="$BUILD_ARCH$arch_name "
            ;;
            *)
                echo "Error: build_arch_configure is wrong when configure building arch environment."
                exit 1
            ;;
        esac
    done
}

function test_arch(){
    local ci_prj=$1
    shift 1
    local arch_list="$@"
    for $arch_name in $arch_list
    do
        case $ci_prj in
            DOPRA_Linux*|*_STORAGE_X86|*_SUSE|EulerLinuxV100R001C10|*_WN)
                if [ "$arch_name" != "x86_64" ];then
                    echo "Error: $arch_name can't build for $ci_prj."
                    exit 1
                fi
            ;;
            EulerOS_V200R005C00*)
                if [ "$arch_name" != "x86_64" -o "$arch_name" != "aarch64" ];then
                    echo "Error: $arch_name can't build for $ci_prj."
                    exit 1
                fi
            ;;
            *)
                echo "Error: $ci_prj unsupport to configure arch."
                exit 1
            ;;
        esac
    done
}

function check_baseline_list(){
    local all_prj_list="$1"
    local prj_conf=$2

    get_prj_list build_baseline_list $prj_conf
    for prj_name in $PRJ_LIST
    do
        echo $all_prj_list | grep $prj_name 1>/dev/null 2>&1
        if [ $? -ne 0 ];then
            echo "$prj_name project not found."
            exit 1
        fi
    done
}

function create_suse_env()
{
    local suse_ver="$1"
    local mount_num=1
    local odd_even=0
    local arch_name=("x86_64" "i586")
    local suse_iso=("SLE-11-$suse_ver-SDK-DVD-i586-GM-DVD1.iso" "SLE-11-$suse_ver-SDK-DVD-x86_64-GM-DVD1.iso"
                "SLES-11-$suse_ver-DVD-i586-GM-DVD1.iso" "SLES-11-$suse_ver-DVD-x86_64-GM-DVD1.iso")

    mkdir -p /srv/tmp/{1,2,3,4}
    for iso_name in ${suse_iso[@]}
    do
        if [ ! -f $BASE_ISO_PATH/$iso_name ];then
            echo "$BASE_ISO_PATH/$iso_name dosen't exist."
            exit 1
        fi
        mount -o loop $BASE_ISO_PATH/$iso_name /srv/tmp/$mount_num
        ((mount_num++))
    done

    META="SUSE:SLE-11:$suse_ver.meta"
    grep "person" $META >/dev/null 2>&1
    if [ $? -eq 0 ];then
        sed -i '/<person userid/d' $META
        sed -i '/<group groupid/d' $META
        sed -i '/<description\/>/a\  <person userid="Admin" role="bugowner"/>\n  <person userid="Admin" role="maintainer"/>' $META
    fi
    osc meta prj SUSE:SLE-11:$suse_ver --file="$META"
    osc meta prjconf SUSE:SLE-11:$suse_ver --file="SUSE:SLE-11:$suse_ver.prjconf"

    mkdir -p $BUILD_PATH/SUSE:SLE-11:$suse_ver/standard/{i586,x86_64}/:full
    mount_num=1
    while [ $mount_num -lt 5 ]
    do
        odd_even=`expr $mount_num % 2`
        cp /srv/tmp/$mount_num/suse/${arch_name[$odd_even]}/*   $BUILD_PATH/SUSE:SLE-11:$suse_ver/standard/${arch_name[$odd_even]}/:full
        cp /srv/tmp/$mount_num/suse/noarch/*   $BUILD_PATH/SUSE:SLE-11:$suse_ver/standard/${arch_name[$odd_even]}/:full
        ((mount_num++))
    done

    mkdir -p /srv/obs/repos/SUSE:/SLE-11:/$suse_ver/standard/{i586,noarch,x86_64}
    for arch_name in i586 x86_64
    do
        cp $BUILD_PATH/SUSE:SLE-11:$suse_ver/standard/$arch_name/:full/*.${arch_name}.rpm /srv/obs/repos/SUSE:/SLE-11:/$suse_ver/standard/$arch_name/
        cp $BUILD_PATH/SUSE:SLE-11:$suse_ver/standard/$arch_name/:full/*.noarch.rpm /srv/obs/repos/SUSE:/SLE-11:/$suse_ver/standard/noarch/
    done

    chown -R obsrun.obsrun $BUILD_PATH
    rcobsscheduler restart
    /usr/lib/obs/server/bs_admin --rescan-repository SUSE:SLE-11:$suse_ver standard x86_64
    /usr/lib/obs/server/bs_admin --rescan-repository SUSE:SLE-11:$suse_ver standard i586
    umount /srv/tmp/1 /srv/tmp/2 /srv/tmp/3 /srv/tmp/4
}

function create_prj()
{
    PROJS="$@"
    for PRODUCT in $PROJS
    do
        META="$PRODUCT.meta"
        sed -i '/<person userid/d' $META
        sed -i '/<group groupid/d' $META
        sed -i '/<description\/>/a\  <person userid="Admin" role="bugowner"/>\n  <person userid="Admin" role="maintainer"/>' $META
        sed  '/<path project/d' $META > $META-tmp
        osc meta prj "$PRODUCT" --file="$META-tmp"
    done

    for PRODUCT in $PROJS
    do
        META="$PRODUCT.meta"
        sed -i '/<person userid/d' $META
        sed -i '/<group groupid/d' $META
        sed -i '/<description\/>/a\  <person userid="Admin" role="bugowner"/>\n  <person userid="Admin" role="maintainer"/>' $META
        PRO_CONF="$PRODUCT.prjconf"
        PROJECT="$PRODUCT"
        PROJECT1="`echo $PROJECT| sed 's/://g'`"
        sed '/<build>/,/<\/build>/ d' $META >${META}-tmp
        sed -i '/<\/project>/i\  <build>\n    <disable/>\n  <\/build>' ${META}-tmp
        osc meta prj "$PROJECT" --file="${META}-tmp"
        osc meta prjconf "$PROJECT" --file="$PRO_CONF"

        rm -rf ${PROJECT}
        osc co ${PROJECT}
        if [ -f ${PROJECT1}.tar.gz ]; then
            tar -xf ${PROJECT1}.tar.gz
        fi
        if ls ${PROJECT1} | grep -v .osc; then
            cp -r ${PROJECT1}/* ${PROJECT}/
            find ${PROJECT}/* -name .osc | xargs rm -rf &>/dev/null
            cd ${PROJECT}
            osc add *
            osc ci -m 'ok'
            cd -
        fi
        for pkg in `ls ${PROJECT1}`
        do
            if [ -f "${PROJECT1}/${pkg}/.osc/_meta" ]; then
                sed -i '/<person userid/d' "${PROJECT1}/${pkg}/.osc/_meta"
                sed -i '/<group groupid/d' "${PROJECT1}/${pkg}/.osc/_meta"
                osc meta pkg "$PROJECT" "$pkg" --file="${PROJECT1}/${pkg}/.osc/_meta"
            fi
        done
        osc meta prj "$PROJECT" --file="${META}"
    done
}

function get_prj_build_result()
{
    flag=0
    projs="$@"
    for pkg in `osc ls $projs`
    do
        osc results $projs $pkg 2> /dev/null | grep 'broken'
        if [ $? -eq 0 ]
        then
           flag=1
           break
        fi
    done
    return $flag
}

function log_info()
{
    echo "$@"
}

function log_warn()
{
    echo "[WARNING] $@"
}

function clean_and_exit()
{

    if [ $1 -ne 0 ]; then
        echo "=========error start========="
        cat $ERROR_LOG
        echo "=========error end========="
    fi
    exit $1
}

function log_error()
{
    echo "[ERROR] $@"
    clean_and_exit 1
}

function run_build_service()
{
    PROJS="$@"
    for pkg in `osc ls $PROJS`
    do
        osc service remoterun $PROJS $pkg 2> /dev/null
    done
}

function create_prj_safe()
{
    set +e
    build_time=3
    PROJS="$@"
    set -e
    create_prj $PROJS
    set +e
    sleep 120
    for((i=1;i<=$build_time;i++))
    do
        get_prj_build_result $PROJS
        ret=$?
        if [ $ret -eq 0 ];then
           log_info "create project $@ success"
           break
        else
            run_build_service $PROJS
        fi
    done
    if [ $ret -ne 0 ];then
        log_error "create project $@ failed"
    fi
    set -e
}

function wait_build_finish()
{
    set +e
    PROJS="$@"
    for pkg in `osc ls $PROJS`
    do
        while true
        do
            osc results $PROJS $pkg 2> /dev/null | egrep "building|blocked"
            ret=$?
            if [ $ret -eq 0 ]
            then
                sleep 60
            else
                break
            fi
        done
    done
    set -e
}

function edit_prjconf(){
    PRJ_CONF=$1
    PRJ_SRC=$2
    PRJ_DEST=$3

    set +e
    grep "$PRJ_SRC" ${PRJ_CONF}.prjconf-tmp 1>/dev/null 2>&1
    if [ $? -eq 0 ];then
         if [ "$status_prj" == "delete" ];then
              sed -i "/$PRJ_SRC/d" ${PRJ_CONF}.prjconf-tmp
         else
              sed -i "s/$PRJ_SRC/$PRJ_DEST/g" ${PRJ_CONF}.prjconf-tmp
         fi
    elif [ "$status_prj" == "enable" ];then
          sed -i "/Macros:/i\\$PRJ_DEST" ${PRJ_CONF}.prjconf-tmp
    else
          set -e
          return 0
    fi
    osc ls | grep $PRJ_CONF >/dev/null 2>&1
    if [ $? -eq 0 ];then
        osc meta prjconf $PRJ_CONF --file="${PRJ_CONF}.prjconf-tmp"
    fi
    set -e
}

function extract_baseline(){
    local build_version=$1
    local all_prj_list="$2"
    GET_BASELINE_LIST=""
    for prj_name in $all_prj_list
    do
        echo $prj_name | grep [B/b]ase[L/l]ine 1>/dev/null 2>&1
        if [ $? -eq 0 ];then
            GET_BASELINE_LIST="$GET_BASELINE_LIST$prj_name "
        fi
    done
    return 0
}

function init_build_env(){
    local prj_name=$1
    local repo_name=$2
    shift 2
    local arch_list="$@"
    local rename_arch=""
    local arch_name=""
    local arch_path=""

    for arch_name in $arch_list
    do
        if [ "$arch_name" == "x86_64_i686" ];then
            rename_arch="i686"
            arch_name=$rename_arch
            arch_name="x86_64"
        elif [ "$arch_name" != "noarch" ];then
            rename_arch="$arch_name"
            arch_path="$rename_arch"
        fi

        cp -an $BASE_ISO_PATH/$arch_path/Packages/*${arch_name}.rpm $BUILD_PATH/$prj_name/$repo_name/$rename_arch/:full
    done
}


function create_centos(){
    local centos_ver=$1
    shift 1
    local arch_list="$@"
    local arch_name=""

    META="CentOS$centos_ver.meta"
    sed -i '/<person userid/d' $META
    sed -i '/<group groupid/d' $META
    sed -i '/<description\/>/a\  <person userid="Admin" role="bugowner"/>\n  <person userid="Admin" role="maintainer"/>' $META
    case $centos_ver in
        7.1|7.2)
            for arch_name in $arch_list
            do
                case $arch_name in
                i686)
                    rm -rf $BUILD_PATH/CentOS$centos_ver:$arch_name/standard/$arch_name/:full
                    mkdir -p $BUILD_PATH/CentOS$centos_ver:$arch_name/standard/$arch_name/:full

                    sed -i '/<person userid/d' CentOS$centos_ver:${arch_name}.meta
                    sed -i '/<group groupid/d' CentOS$centos_ver:${arch_name}.meta
                        osc meta prj CentOS$centos_ver:${arch_name} --file="CentOS$centos_ver:${arch_name}.meta"
                        osc meta prjconf CentOS$centos_ver:${arch_name} --file="CentOS$centos_ver:${arch_name}.prjconf"
                    sleep 10
                    init_build_env CentOS$centos_ver:${arch_name} standard ${arch_name} noarch
                ;;
                x86_64)
                    rm -rf $BUILD_PATH/CentOS$centos_ver/standard/{i686,$arch_name}/:full
                     mkdir -p $BUILD_PATH/CentOS$centos_ver/standard/{i686,$arch_name}/:full

                       sed -i '/<person userid/d' CentOS$centos_ver.meta
                       sed -i '/<group groupid/d' CentOS$centos_ver.meta
                       osc meta prj CentOS$centos_ver --file="CentOS${centos_ver}.meta"
                       osc meta prjconf CentOS$centos_ver --file="CentOS${centos_ver}.prjconf"
                       sleep 10
                    init_build_env CentOS$centos_ver standard i686 noarch
                    init_build_env CentOS$centos_ver standard ${arch_name} noarch
                ;;
                *)
                ;;
                esac
            done
        ;;
        7.3)
               osc meta prj CentOS$centos_ver --file="CentOS${centos_ver}.meta"
               osc meta prjconf CentOS$centos_ver --file="CentOS${centos_ver}.prjconf"
            sleep 10

            for build_arch in $arch_list
            do
                rm -rf /srv/obs/build/CentOS$centos_ver/standard/$build_arch/:full
                mkdir -p /srv/obs/build/CentOS$centos_ver/standard/$build_arch/:full

                case $build_arch in
                i686|x86_64)
                    local build_prj_list="centos_7.3_x86_64_update centos_7.3_extend 20170421"
                    if [ "$build_arch" == "i686" ];then
                        init_build_env CentOS$centos_ver standard x86_64_i686 noarch
                        build_prj_list="$build_prj_list centos_7.3_i686_update"
                    fi
                    init_build_env CentOS$centos_ver standard $build_arch noarch

                    for tmp_prj in $build_prj_list
                    do
                        case $tmp_prj in
                            20170421)
                                cp $tmp_prj/* $BUILD_PATH/CentOS$centos_ver/standard/$build_arch/:full
                            ;;
                            centos_${centos_ver}_i686_update)
                                cp centos_${centos_ver}_i686_update/*.rpm $BUILD_PATH/CentOS$centos_ver/standard/$build_arch/:full
                            ;;
                            *)
                                for arch_name in $build_arch noarch
                                do
                                    if [ "$tmp_prj" == "centos_7.3_extend" ];then
                                        cp $tmp_prj/x86_64/*.${arch_name}.rpm $BUILD_PATH/CentOS$centos_ver/standard/$build_arch/:full
                                    else
                                        cp $tmp_prj/*.${arch_name}.rpm $BUILD_PATH/CentOS$centos_ver/standard/$build_arch/:full
                                    fi
                                done
                            ;;
                        esac
                    done
                ;;
                aarch64)
                    cp $BASE_ISO_PATH/$build_arch/Packages/*.rpm $BUILD_PATH/CentOS${centos_ver}/standard/$build_arch/:full
                    cp centos_${centos_ver}_${build_arch}_update/*.rpm $BUILD_PATH/CentOS${centos_ver}/standard/$build_arch/:full
                    cp centos_${centos_ver}_extend/$build_arch/*.rpm $BUILD_PATH/CentOS${centos_ver}/standard/$build_arch/:full
                ;;
                esac
                rm -rf centos_${centos_ver}_${build_arch}_update
            done
        ;;
        7.4|7.5)
            osc meta prj CentOS$centos_ver --file="CentOS${centos_ver}.meta"
            osc meta prjconf CentOS$centos_ver --file="CentOS${centos_ver}.prjconf"
            for arch_name in $arch_list
            do
                rm -rf $BUILD_PATH/CentOS$centos_ver/standard/$arch_name/:full
                mkdir -p $BUILD_PATH/CentOS$centos_ver/standard/$arch_name/:full
                sleep 10
                init_build_env CentOS$centos_ver standard ${arch_name} noarch
            done
        ;;
    esac

    pushd $BUILD_PATH
        chown -R obsrun:obsrun CentOS$centos_ver
    popd
    for arch_name in $arch_list
    do
        /usr/lib/obs/server/bs_admin  --rescan-repository CentOS$centos_ver standard $arch_name
    done
}

function create_Fedora(){
    local Fedora_ver=$1
    shift 1
    local arch_list="$@"
    local arch_name=""

    META="Fedora-$Fedora_ver.meta"
    sed -i '/<person userid/d' $META
    sed -i '/<group groupid/d' $META
    sed -i '/<description\/>/a\  <person userid="Admin" role="bugowner"/>\n  <person userid="Admin" role="maintainer"/>' $META
    case $Fedora_ver in
        29-1.2)
            osc meta prj Fedora-$Fedora_ver --file="Fedora-${Fedora_ver}.meta"
            osc meta prjconf Fedora-$Fedora_ver --file="Fedora-${Fedora_ver}.prjconf"

            for arch_name in $arch_list
            do
                rm -rf $BUILD_PATH/Fedora-$Fedora_ver/standard/$arch_name/:full
                mkdir -p $BUILD_PATH/Fedora-$Fedora_ver/standard/$arch_name/:full
                find $BASE_ISO_PATH/standard/$arch_name/\:full/ -name "*.rpm" | xargs -i cp -an {} $BUILD_PATH/Fedora-$Fedora_ver/standard/$arch_name/\:full
            done

        ;;
    esac

    chown -R obsrun:obsrun $BUILD_PATH/Fedora-$Fedora_ver

    for arch_name in $arch_list
    do
        /usr/lib/obs/server/bs_admin  --rescan-repository Fedora-$Fedora_ver standard $arch_name
    done
    rcobsscheduler restart
}

function create_build_centos(){
    local centos_ver=$1
    case $centos_ver in
        7.1)
            ISO_I686="CentOS-7-i386-Everything-1503.iso"
            ISO_X86_64="CentOS-7-x86_64-Everything-1503-01.iso"
        ;;
        7.2)
            ISO_I686="CentOS-7-i386-Everything-1511.iso"
            ISO_X86_64="CentOS-7-x86_64-Everything-1511.iso"
        ;;
        7.3)
            ISO_I686="CentOS-7-i386-Everything-1611.iso"
            ISO_X86_64="CentOS-7-x86_64-Everything-1611.iso"
            ISO_AARCH64="CentOS-7-aarch64-Everything.iso"
            local tar_list="centos_7.3_extend 20170421"

            for tar_name in $tar_list centos_7.3_{x86_64,i686,aarch64}_update
            do
                tar xf $BASE_ISO_PATH/${tar_name}.tar.gz -C $CUR_PATH
            done
        ;;
        7.4)
            ISO_I686="CentOS-7-i386-Everything-1708.iso"
            ISO_X86_64="CentOS-7-x86_64-Everything-1708.iso"
            ISO_AARCH64="CentOS-7-aarch64-Everything.iso"
            ;;
        7.5)
            ISO_I686="CentOS-7-i386-Everything-1804.iso"
            ISO_X86_64="CentOS-7-x86_64-Everything-1804.iso"
            ISO_AARCH64=""
            ;;
        *)
        ;;
    esac

    shift 1
    local num=0
    local arch_name=($@)
    for iso_arch in $ISO_I686 $ISO_X86_64 $ISO_AARCH64
    do
        if [ ! -f $BASE_ISO_PATH/$iso_arch ];then
            echo "$BASE_ISO_PATH/$iso_arch dosen't exist."
            record_log $LINENO ERROR "$BASE_ISO_PATH/$iso_arch dosen't exist."
            exit 1
        fi

        mkdir -p $BASE_ISO_PATH/${arch_name[$num]}
        mount $BASE_ISO_PATH/$iso_arch $BASE_ISO_PATH/${arch_name[$num]} 2>/dev/null 1>&2
        if [ $? -ne 0 ];then
            echo "$BASE_ISO_PATH/$iso_arch mount failed."
            record_log $LINENO ERROR "$BASE_ISO_PATH/$iso_arch mount failed."
            exit 1
        fi

        ((num++))
    done

    create_centos $centos_ver ${arch_name[@]}

    num=0
    for iso_arch in ${arch_name[@]}
    do
        umount $BASE_ISO_PATH/${arch_name[$num]} 2>/dev/null 1>&2
        rm -rf $BASE_ISO_PATH/${arch_name[$num]}
        ((num++))
    done

    if [ "$centos_ver" == "7.3" ];then
        rm -rf 20170421 centos_7.3_extend
    fi
    systemctl restart obsscheduler.service
}

function create_build_Fedora(){
    local Fedora_ver=$1
    case $Fedora_ver in
        29-1.2)
            standard="standard.tar.gz"
        ;;
        *)
        ;;
    esac

    shift 1
    local arch_name=($@)

    if [ ! -f $BASE_ISO_PATH/$standard ];then
            record_log $LINENO ERROR "$standard dosen't exist."
            exit 1
    fi

    tar -xf $BASE_ISO_PATH/$standard -C $BASE_ISO_PATH

    create_Fedora $Fedora_ver ${arch_name[@]}
}

function modify_prj(){
    prj_name=$1
    status_prj=$2
    shift 2
    cp ${prj_name}.prjconf ${prj_name}.prjconf-tmp
    for modify_data in "$@"
    do
        case $status_prj in
            disable)
                edit_prjconf $prj_name "$modify_data" "#$modify_data"
            ;;
            enable)
                edit_prjconf $prj_name "#$modify_data" "$modify_data"
            ;;
            delete)
                edit_prjconf $prj_name "$modify_data"
            ;;
            *)
            ;;
        esac
    done
    rm ${prj_name}.prjconf-tmp
}

function wait_published(){
    pub_prj=$1
    pub_repo=$2
    shift 2

    set +e
    for pub_arch in $@
    do
        while true
        do
            osc results $pub_prj | grep "$pub_repo $pub_arch (published)" 1>/dev/null 2>&1
            if [ $? -eq  0 ];then
                break
            else
                sleep 3
            fi
        done
    done
    set -e
}

XML_DATA=""
function get_data_from_xml(){
    XML_DATA=""
    meta_name=$1
    take_sec="<$2"
    set +e
    case $2 in
    repository)
        filter_str_start="\""
        filter_str_end="\""
        ;;
    arch)
        filter_str_start=">"
        filter_str_end="<"
        ;;
    *)
        return 1
        ;;
    esac
    while read line
    do
        echo $line | grep "$take_sec" 1>/dev/null 2>&1
        if [ $? -eq 0 ];then
            tmp_str=${line#*$filter_str_start}
            tmp_str=${tmp_str%%${filter_str_end}*}
            XML_DATA="$XML_DATA $tmp_str"
        fi
    done < ${meta_name}.meta
    set -e
    return 0
}

XML_ARCH_LIST=""
function get_arch_by_repo(){
    meta_name=$1
    take_repo="$2"
    start_flag=1
    XML_ARCH_LIST=""
    set +e
    while read line
    do
        echo $line | grep "<repository" 1>/dev/null 2>&1
        if [ $? -eq 0 ];then
            tmp_str=${line#*"\""}
            tmp_str=${tmp_str%%"\""*}
            if [ "$tmp_str" == "$take_repo" ];then
                start_flag=0
                continue
            elif [ $start_flag -eq 0 ];then
                break
            fi
        fi

        echo $line | grep "<arch" 1>/dev/null 2>&1
        if [ $start_flag -eq 0 -a $? -eq 0 ];then
            tmp_str=${line#*">"}
            tmp_str=${tmp_str%%"<"*}
            XML_ARCH_LIST="$XML_ARCH_LIST $tmp_str"
        fi
    done < ${meta_name}.meta
    set -e
}

function wait_status_update(){
    PRJ_NAME=$1
    PRJ_REPO=$2
    shift 2

    set +e
    for prj_arch in $@
    do
        while true
        do
            osc results $PRJ_NAME -r $PRJ_REPO -a $prj_arch --csv | grep "building"
            if [ $? -eq 0 ];then
                break
            else
                sleep 3
            fi
        done
    done
    set -e
}

function fixed_package(){
    PRJ_NAME=$1
    PRJ_REPO=$2
    PRJ_ARCH=$3
    PKG_STAT=$4
    RESOLVE_BEFORE=""
    set +e
    while true
    do
        failed_list=`osc results $PRJ_NAME -r $PRJ_REPO -a $PRJ_ARCH --csv | grep $PKG_STAT |sed  "s/;$PKG_STAT//g"`
        if [ -z "$failed_list" ];then
            break
        fi

        osc rebuild $PRJ_NAME -f -r $PRJ_REPO -a $PRJ_ARCH

        wait_status_update $PRJ_NAME $PRJ_REPO $PRJ_ARCH
        wait_published $PRJ_NAME $PRJ_REPO $PRJ_ARCH
        if [ "$RESOLVE_BEFORE" == "$failed_list" ];then
            break
        fi
        RESOLVE_BEFORE="$failed_list"
    done
    set -e
}

function create_repos()
{
    PRODUCT=$1
    REPO=$2
    PROJECT=`echo $PRODUCT| sed 's/://g'`
    repos_name=`echo $PRODUCT| sed 's/:/:\//g'`
    mkdir -p /srv/obs/repos/$repos_name/$REPO/
    chown -R obsrun:obsrun /srv/obs/repos/$repos_name/$REPO/
    if [ -d $PROJECT/$REPO ];then
        nums_file=`ls $PROJECT/$REPO | wc -l`
        if [ $nums_file -gt 1 ];then
            cp -r $PROJECT/$REPO/* /srv/obs/repos/$repos_name/$REPO/
        fi
    fi
    createrepo --worker=10 --update /srv/obs/repos/$repos_name/$REPO/ --cachedir=/srv/obs/repos/$repos_name/$REPO/repocache
}

function create_build()
{
    PRODUCT=$1
    REPO=$2
    shift;shift
    ARCHLIST=$@

    META="$PRODUCT.meta"
    sed -i '/<person userid/d' $META
    sed -i '/<group groupid/d' $META
    sed -i '/<description\/>/a\  <person userid="Admin" role="bugowner"/>\n  <person userid="Admin" role="maintainer"/>' $META
    PRO_CONF="$PRODUCT.prjconf"
    PROJECT="$PRODUCT"
    PROJECT1="`echo $PROJECT| sed 's/://g'`"
    local cp_src_path=""
    osc meta prj "$PROJECT" --file="$META"
    osc meta prjconf "$PROJECT" --file="$PRO_CONF"
    for line in $ARCHLIST
    do
        mkdir -p $BUILD_PATH/$PROJECT/$REPO/$line/:full
        if [ "$REPO" == "standard_ARM64" ];then
            cp_src_path="$PROJECT1/standard_x86_64"
        else
            cp_src_path="$PROJECT1/$REPO"
        fi

        if [ -d $cp_src_path/$line ];then
            nums_file=`ls $cp_src_path/$line | wc -l`
            if [ $nums_file -gt 1 ];then
                cp $cp_src_path/$line/* $BUILD_PATH/$PROJECT/$REPO/$line/:full
                   if [ -d $cp_src_path/noarch ]; then
                    nums_file=`ls $cp_src_path/noarch/* | wc -l`
                    if [ $nums_file -gt 1 ];then
                        cp $cp_src_path/noarch/* $BUILD_PATH/$PROJECT/$REPO/$line/:full
                    fi
                   fi
            fi
        fi

        chown -R obsrun.obsrun $BUILD_PATH
        /usr/lib/obs/server/bs_admin --rescan-repository $PROJECT $REPO $line
    done
}

function create_base()
{
    PRODUCT=$1
    REPO=$2
    create_build $@
    create_repos $PRODUCT $REPO
}

function backup_meta(){
    prj_name=$1
    backup_name=$2
    cp ${prj_name}.meta ${backup_name}.meta
}

function backup_recover_meta(){
    prj_name=$1
    backup_name=$2
    cp ${backup_name}.meta ${prj_name}.meta
    rm -rf ${backup_name}.meta
}

function edit_meta_ex(){
    prj_name=$1
    start_str=$2
    end_str=$3
    start_num=`grep -n $start_str ${prj_name}.meta | gawk '{print $1}'`
    start_num=`expr match $start_num '\([0-9]*\)'`
    end_num=`grep -n -A 100 $start_str ${prj_name}.meta | grep "$end_str" | head -n 1 | gawk '{print $1}'`
    end_num=`expr match $end_num '\([0-9]*\)'`

    sed -i "$start_num, ${end_num}d" ${prj_name}.meta
}

function edit_meta(){
    prj_name=$1
    edit_contain=$2
    osc meta prj $prj_name | sed "$edit_contain" >${prj_name}.meta-tmp && \
    osc meta prj $prj_name --file="${prj_name}.meta-tmp" && rm -rf "${prj_name}.meta-tmp"
    return $?
}

function get_create_tar_list(){
    prj_conf=$1
    CREATE_TAR_LIST=""
    TAR_STD_LIST=`cat common_function.sh | grep "function\ " | sed "s/function\ //g" | sed "s/()//g"`

    if [ -z "$TAR_STD_LIST" ];then
        TAR_STD_LIST=`ls *.sh | sed "s/.sh//g"`
    fi

    grep create_tar_list $prj_conf >/dev/null 2>&1
    if [ $? -ne 0 ];then
        return 1
    fi

    get_prj_list create_tar_list $prj_conf
    for line in $PRJ_LIST
    do
        if [ -z "$line" ];then
            return 1
        fi

        echo $line | grep "=" 1>/dev/null 2>&1
        if [ $? -ne 0 ];then
            echo "Warning: $line is Invalid configuration."
            continue;
        fi

        enable_list=${line%%"="*}
        echo $TAR_STD_LIST | grep "$enable_list" 1>/dev/null 2>&1
        if [ $? -ne 0 ];then
            echo "Warning: No supporting $enable_list now."
            continue
        fi

        enable_flag=${line##*"="}
        if [ "$enable_flag" == "yes" -o "$enable_flag" == "no" ];then
            if [ "$enable_flag" == "yes" ];then
                CREATE_TAR_LIST="$CREATE_TAR_LIST$enable_list "
            fi
        else
            CREATE_TAR_LIST="$CREATE_TAR_LIST$enable_list "
        fi
    done
}

PATH_FROM_TRANS=""
function trans_to_path_for_prj_name(){
    PATH_FROM_TRANS=""
    src_prj=$1
    PATH_FROM_TRANS=`echo $src_prj | sed 's/:/:\//g'`
}

function run_script()
{
    script=$1
    shift
    args="$@"
    log_info "Start run $script $args at `date`"
    eval $script $args
    if [ $? -ne 0 ]; then
        log_error "Run $script $args failed at `date`"
    else
        log_info "Finished run $script $args at `date`"
    fi
}

